package com.ruoyi.dict.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.domain.dict.DictDevice;
import com.ruoyi.common.domain.dict.view.DictDeviceView;
import com.ruoyi.common.domain.dict.vo.DictDeviceVo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.dict.mapper.DictDeviceMapper;
import com.ruoyi.dict.mapper.DictDeviceViewMapper;
import com.ruoyi.dict.service.IDictDeviceService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 字典-设备 服务层实现
 *
 * @author ruoyi
 * @date 2022-02-23
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class DictDeviceServiceImpl extends ServiceImpl<DictDeviceMapper, DictDevice> implements IDictDeviceService {


    private final DictDeviceViewMapper dictDeviceViewMapper;



    @Override
    public List<DictDeviceVo> getDictDeviceVoList(String deviceGroupName, String deviceName, String litStatus) {

        List<DictDeviceView> dictDeviceViewList = dictDeviceViewMapper.selectList(Wrappers.lambdaQuery(DictDeviceView.class)
                .like(StringUtils.isNotBlank(deviceGroupName), DictDeviceView::getDeviceGroupName, deviceGroupName)
                .like(StringUtils.isNotBlank(deviceName), DictDeviceView::getDeviceName, deviceName)
                .eq(StringUtils.isNotBlank(litStatus), DictDeviceView::getLitStatus, litStatus)
                .orderByAsc(DictDeviceView::getGroupOrderNum)
                .orderByAsc(DictDeviceView::getOrderNum)
                .orderByAsc(DictDeviceView::getDeviceId));

        List<DictDeviceVo> dictDeviceVoList = new ArrayList<>();
        Map<String, List<DictDeviceView>> map = new LinkedHashMap<>();
        List<DictDeviceView> unGroupList = new ArrayList<>();
        for (DictDeviceView dictDeviceView : dictDeviceViewList) {
            String groupName = dictDeviceView.getDeviceGroupName();
            if (StringUtils.isBlank(groupName)) {
                unGroupList.add(dictDeviceView);
                continue;
            }
            if (map.containsKey(groupName)) {
                List<DictDeviceView> dictDeviceViews = map.get(groupName);
                dictDeviceViews.add(dictDeviceView);
            } else {
                List<DictDeviceView> newDictDeviceViewList = new ArrayList<>();
                newDictDeviceViewList.add(dictDeviceView);
                map.put(groupName, newDictDeviceViewList);
            }
        }
        if (unGroupList.size() > 0) {
            map.put("未分组", unGroupList);
        }
        map.forEach((k, v) -> {
            dictDeviceVoList.add(new DictDeviceVo(k, v));
        });
        return dictDeviceVoList;


    }


}